<template>
	<div class="p-0">
		<n-card class="upload-item" @click="showModal = true">
			<n-icon :component="addIcon" size="26"></n-icon>
		</n-card>
		
		<n-modal v-model:show="showModal"
		         transform-origin="center"
		         :on-after-leave="closeModal"
		         :auto-focus="false"
		         :mask-closable="false">
			<n-spin :show="bodyLoading">
				<n-card
					style="width: 52rem"
					closable
					@close="closeModal">
					<template #header>
						图片库
					</template>
					
					<n-layout has-sider style="height: 30rem;">
						<n-layout-sider bordered
						                width="9rem"
						                content-style="display:flex;display: flex;flex-direction: column;justify-content: space-between">
							<n-scrollbar x-scrollable>
								<div>
									<n-tree
										block-line
										:data="groups"
										:default-selected-keys="['all']"
										selectable
										:cancelable="false"
										:key-field="'id'"
										:label-field="'name'"
										:node-props="groupTreeProps"
									/>
								</div>
							</n-scrollbar>
							<div>
								<n-button quaternary type="primary" @click="showAddGroup = true">新增分组</n-button>
							</div>
						</n-layout-sider>
						<n-layout>
							<n-layout-header class="px-3 py-1">
								<div class="flex flex-row justify-between">
									<div>
										<n-space>
											<n-input v-model:value="keyword"
											         type="text"
											         placeholder="搜索"
											         clearable
											         style="width: 12rem"/>
											
											<n-button type="primary" ghost @click="searchData">
												搜索
											</n-button>
										</n-space>
									</div>
									<div class="flex justify-between">
										<n-button-group class="mr-3" v-if="selectedIds.length">
											<n-button>删除</n-button>
											<n-button>移动</n-button>
										</n-button-group>
										<n-upload :action="uploadAction"
										          :show-file-list="false"
										          @finish="uploadFinish"
										          multiple
										          @before-upload="beforeUpload"
										          :data="{ 'fileType': fileType }">
											<n-button type="primary" ghost>
												<template #icon>
													<n-icon :component="uploadIcon"></n-icon>
												</template>
												上传
											</n-button>
										</n-upload>
									</div>
								</div>
							</n-layout-header>
							<n-layout-content content-style="height:23rem;" class="p-3">
								<n-grid cols="5" responsive="screen" class="p-1">
									<n-grid-item v-for="(item, index) in data" :key="index">
										<div class="file-item" @click="selectItem(item)">
											<!--选中遮罩-->
											<div class="selected flex justify-center items-center animate__animated animate__zoomIn animate_duration"
											     v-if="selectedIds.indexOf(item.id) > -1">
												<n-icon :component="checkIcon" size="30" color="#f5f5f5"></n-icon>
											</div>
											<!--文件展示-->
											<div class="file">
												<n-image :src="item.file_path" object-fit="fill" preview-disabled/>
											</div>
											<n-ellipsis style="max-width: 5.5rem; font-size:10px">
												{{ item.file_name }}
											</n-ellipsis>
										</div>
									</n-grid-item>
								</n-grid>
							</n-layout-content>
							<n-layout-footer style="background:transparent;" class="flex felx-row justify-between items-center">
								<div class="pl-3">
									<div v-if="selectedIds.length">
										已选择{{ selectedIds.length }}项
									</div>
								</div>
								<div>
									<n-pagination v-bind="pagination" @update:page="chagePage" :page-slot="5"/>
								</div>
							</n-layout-footer>
						</n-layout>
					</n-layout>
					
					<template #footer>
						<div class="flex flex-row justify-end">
							<n-space>
								<n-button @click="closeModal">
									取消
								</n-button>
								<n-button type="primary">
									确定
								</n-button>
							</n-space>
						</div>
					</template>
				</n-card>
			</n-spin>
		</n-modal>
		
		<!--添加分组-->
		<n-modal v-model:show="showAddGroup"
		         transform-origin="center"
		         :on-after-leave="closeGroupModal"
		         :mask-closable="false">
			<n-card
				style="width: 600px"
				title="添加分组"
				closable
				@close="closeGroupModal">
				<n-form
					ref="groupRef"
					:label-width="80"
					:model="groupValue"
					:rules="groupRules"
					label-placement="left"
					label-width="auto"
				>
					<n-form-item label="分组名称" path="name">
						<n-input v-model:value="groupValue.name" placeholder="输入分组名称"/>
					</n-form-item>
					<n-form-item label="上级分组" path="parent_id">
						<n-tree-select
							cascade
							clearable
							:options="groupOptions"
							label-field="name"
							key-field="id"
							placeholder="顶级分类"
							v-model:value="groupValue.parent_id"
						/>
					</n-form-item>
					<n-form-item label="排序" path="sort">
						<n-input-number v-model:value="groupValue.sort" :min="0"/>
					</n-form-item>
				</n-form>
				<template #footer>
					<div class="flex justify-end">
						<n-button ghost class="mr-5" @click="closeGroupModal">取 消</n-button>
						<n-button type="primary" @click="submitGroup">提 交</n-button>
					</div>
				</template>
			</n-card>
		</n-modal>
	</div>
</template>

<script lang="ts" setup>
import {ionicons5Icon} from "@/utils/icon"
import {TreeOption, useMessage, useThemeVars} from "naive-ui"
import {reactive, ref} from "vue"
import {fileLibraryGroup, fileLibrary} from "@/api/api"


const theme = useThemeVars()
const message = useMessage()

const addIcon = ionicons5Icon("Add")
const uploadIcon = ionicons5Icon("CloudUploadOutline")
const checkIcon = ionicons5Icon("CheckmarkCircleOutline")
const uploadAction = fileLibrary.uploadAction

const showAddGroup = ref(false)
const groupOptions = ref([])
const groupRef = ref<any>(null)
const showModal = ref(false)

const keyword = ref("")
const groupId = ref("")
const page = ref(1)
const groups: any = ref([])
// image:图片 video:视频 annex:附件
const fileType = ref("image")

const groupValue = ref({
	name: "",
	parent_id: 0,
	sort: 50,
})

// 关闭分组modal
const closeGroupModal = () => {
	showAddGroup.value = false
	
	groupValue.value = {
		name: "",
		parent_id: 0,
		sort: 50,
	}
}

const groupRules = {
	name: {
		required: true,
		message: "请输入分组名称",
		trigger: "input",
	},
}

const closeModal = () => {
	showModal.value = false
	selectedIds.value = []
	selected.value = []
}

const getGroups = () => {
	fileLibraryGroup.list({}).then((res) => {
		let data = res.data || []
		data.unshift({
			id: "unknow",
			name: "未分组",
		})
		data.unshift({
			id: "all",
			name: "全部",
		})
		groups.value = data
		groupOptions.value = res.data
	})
}
getGroups()

// 提交分组
const submitGroup = (e: MouseEvent) => {
	e.preventDefault()
	groupRef.value?.validate((errors: unknown) => {
		if (!errors) {
			fileLibraryGroup.store(groupValue.value).then((res: any) => {
				if (res.code == 200) {
					message.success(res.message)
					closeGroupModal()
					getGroups()
				} else {
					message.error(res.message)
				}
			})
		}
	})
}

const data = ref<any>([])
const bodyLoading = ref(false)
// 当前页
let currentPage = 1
// 每页数量
let pageSize = 15
// 总条数
let total = 0

// 分页
const pagination = reactive<any>({
	pageSize: pageSize,
	itemCount: 0,
	showQuickJumper: true,
	prefix: () => {
		return `共 ${pagination.itemCount} 条`
	},
})

const initList = () => {
	bodyLoading.value = true
	let params = {
		page: currentPage,
		page_size: pageSize,
		file_type: fileType.value,
		keyword: keyword.value,
		group_id: groupId.value
	}
	console.log(params)
	
	fileLibrary.list(params).then((res) => {
		data.value = res.data.list
		
		pagination.page = res.data.page
		pagination.itemCount = res.data.total
		pagination.pageSize = res.data.page_size
		
		bodyLoading.value = false
	})
}
initList()

// 分组树事件
const groupTreeProps = (data: any) => {
	return {
		onClick() {
			groupId.value = data.option.id
			initList()
		}
	}
}

// 搜索
const searchData = () => {
	currentPage = 1
	initList()
}

// 分页改变
const chagePage = (page: number) => {
	currentPage = page
	initList()
}

// 上传中
let uploading = [] as any

// 上传前
const beforeUpload = (file: any) => {
	uploading.push(file)
	bodyLoading.value = true
}

// 上传完成
const uploadFinish = (res: any) => {
	let result = JSON.parse(res.event.target.response)
	if (result.code != 200) {
		message.error(result.message)
	} else {
		uploading.pop()
		// 全部上传完成
		if (uploading.length === 0) {
			bodyLoading.value = false
			
			message.success(result.message)
			
			currentPage = 1
			initList()
		}
	}
}

// 选中的文件
const selected = ref<any>([])
const selectedIds = ref<any>([])

// 选择
const selectItem = (item: any) => {
	let index = selectedIds.value.indexOf(item.id)
	if (index > -1) {
		selectedIds.value.splice(index, 1)
		selected.value.splice(index, 1)
	} else {
		selected.value.push(item)
		selectedIds.value.push(item.id)
	}
}
</script>

<style lang="scss" scoped>
.upload-item {
	width: 80px;
	height: 80px;
	border-style: dashed;
	border-color: #ccc;
	color: #ccc;
	display: flex !important;
	flex-direction: row;
	justify-content: center;
	align-items: center;
	padding: 0;
	cursor: pointer;
}

.upload-item:hover {
	border-color: v-bind('theme.primaryColor');
	color: v-bind('theme.primaryColor');
}

.file-item {
	border: 1px solid #e5e7eb;
	border-radius: 3px;
	width: 7rem;
	height: 7rem;
	padding: 5px;
	margin-bottom: 8px;
	cursor: pointer;
	position: relative;
	
	.selected {
		position: absolute;
		width: 100%;
		height: 100%;
		background: #08080857;
		border-radius: 3px;
		margin-top: -5px;
		margin-left: -5px;
	}
	
	.file {
		width: 6rem;
		height: 5rem;
		overflow: hidden;
		margin-left: auto;
		margin-right: auto;
	}
}

.file-item:hover {
	border-color: var(--n-color-target);
}

.animate_duration {
	animation-duration: 0.2s;
}
</style>
